<template>
    <section class="content">
        <Panel :expandable="false" :expand="true">
            <template slot="title">收汇申请表头</template>
            <template slot="body">
                <el-form ref="form" label-width="100px" :model="this" :rules="rules">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="收款账户">
                                <el-select v-model="receiverNumber" class="full-cell">
                                    <el-option v-for="s in shopList" :label="s" :key="s" :value="s"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="申报总额" prop="applyTotalAmount">
                                <el-input v-model.number="applyTotalAmount">
                                    <template slot="append">USD</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-form-item label="日期范围" prop="orderDate">
                                <el-date-picker
                                    v-model="orderDate"
                                    :type="datetimeType"
                                    range-separator="至"
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期"
                                    class="full-cell"
                                    :value-format="datetimeValueFormat"
                                    >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="3" style="padding-left: 12px">
                            <el-button @click="handleSearch" type="success">筛选订单</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </template>
        </Panel>
        <Panel :expandable="false" :expand="true" :hasTitle="false">
            <template slot="body">
                <el-form label-width="70px">
                    <el-row :gutter="12">
                        <el-col :span="7">
                            <el-form-item label="订单编号">
                                <el-input v-model="orderNumber" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="9">
                            <el-button type="success" @click="handleSearchByOrderNumber">搜索</el-button>
                            <el-button type="primary" :disabled="buttondisabled" @click="handleCommit">申请收款</el-button>
                            <el-button @click="handleDownload">表头文件导出</el-button>
                        </el-col>
                        <el-col :span="6" style="text-align: right">
                            <div style="padding-top: 10px">总金额：{{totalAmount}}</div>
                        </el-col>
                    </el-row>
                </el-form>

                <el-table :data="subList" header-row-class-name="header-class">
                    <el-table-column align="center" prop="orderCreated" label="订单日期"></el-table-column>
                    <el-table-column label="订单编号" align="center">
                        <template slot-scope="scope">
                            <span :style="{'color': scope.row.isInResult? 'red': ''}">{{scope.row.orderId}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" prop="total" label="订单金额"></el-table-column>
                    <el-table-column align="center" prop="declareNo" label="报关单号"></el-table-column>
                    <el-table-column align="center" label="操作">
                        <template slot-scope="scope">
                            <el-button type="text" icon="iconfont rticon-shanchu" @click="handleDelete(scope.row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="clear-fix">
                    <el-pagination
                        style="float: right; margin-top: 20px;"
                        background
                        layout="total, prev, pager, next"
                        @current-change="handleCurrentChange"
                        @prev-click="handleCurrentChange"
                        @next-click="handleCurrentChange"
                        :current-page="searchParam.page"
                        :page-size="searchParam.rows"
                        :total="searchParam.total">
                    </el-pagination>
                </div>
            </template>
        </Panel>
    </section>
</template>
<script>
import Panel from '@/components/common/panel'
import instance from '@/api/index.js'
import apiUrls from '@/js/common/apiUrls'
import ClientPagination from '@/js/common/ClientPagination'
import {floatAdd, download, datetimeType, datetimeValueFormat} from '@/js/util'

export default {
    name: "preaudit",
    components: {
        Panel
    },
    data() {
        return {
            datetimeType: datetimeType,
            datetimeValueFormat: datetimeValueFormat,
            list: [],
            subList: [],
            deletedList: [],
            receiverNumber: "",
            orderDate: "",
            orderNumber: "",
            searchParam: {
                page: 1,
                total: 0,
                rows: 10
            },
            shopList: [],
            applyTotalAmount: "",
            rules: {
                applyTotalAmount: [{
                    required: true,
                    type: "number",
                    message: "申报金额必填！",
                    trigger: "blur"
                }],

                // orderDate: [{
                //     required: true,
                //     message: "时间段是必填！",
                //     trigger: "blur"
                // }]
            },
          buttondisabled: true,
        };
    },
    methods: {
        padding(n) {
            if(n < 10) {
                return "0" + n;
            } else {
                return "" + n;
            }
        },
        getDateStr(date) {
            if(date) {
                return date.getFullYear() + "-" + this.padding(date.getMonth()+1) + "-" + this.padding(date.getDate());
            }
        },
        handleSearch() {
            let self = this;
            console.log("orderDate: ", this.orderDate);
            this.$refs.form.validate((valid)=>{
                if(valid) {
                    // this.begin = this.getDateStr(this.orderDate && this.orderDate[0]);
                    // this.end = this.getDateStr(this.orderDate && this.orderDate[1]);
                    this.begin = this.orderDate && this.orderDate[0];
                    this.end = this.orderDate && this.orderDate[1];
                    let param = Object.assign({
                        account: this.receiverNumber || null,
                        total: this.applyTotalAmount,
                        begin: this.begin || null,
                        end: this.end || null
                    });
                    self.deletedList = [];

                    instance({
                        method: 'post',
                        url: apiUrls.receive.declareOrderList,
                        params: param
                    }).then(function (data) {
                        if(data.data.success){
                            self.list = self.clientPagination.data = data.data.data;
                            self.handleSearchByOrderNumber();
                          self.buttondisabled = self.list.length> 0? false: true;
                        }
                    }).catch(function (err) {
                        console.log(err)
                    });
                }
            });

        },

        handleSearchByOrderNumber() {
            let orderNumber = this.orderNumber;
            this.clientPagination.search((item)=>{
                return orderNumber != "" && item.orderId.toLowerCase().indexOf(orderNumber.toLowerCase()) > -1;
            });
            this.searchParam.page = 1;
            this.subList = this.clientPagination.subList;
            this.searchParam.total = this.clientPagination.searchParam.total;
        },

        handleDelete(item) {
            this.clientPagination.handleDelete(item);
            this.subList = this.clientPagination.subList;
            this.searchParam.total = this.clientPagination.searchParam.total;
        },

        handleCurrentChange(pageIndex) {
            this.searchParam.page = pageIndex;

            this.clientPagination.handleCurrentChange(pageIndex);
            this.subList = this.clientPagination.subList;
            this.searchParam.total = this.clientPagination.searchParam.total;
        },

        getCurrentDateStr() {
            let now = new Date();
            return now.getFullYear() + this.padding(now.getMonth()+1) + this.padding(now.getDate()) + this.padding(now.getHours()) + this.padding(now.getMinutes());
        },

        // 提交审核
        handleCommit() {
            let self = this;
            let param = {
                account: this.receiverNumber,
                begin: this.begin,
                end: this.end,
                total: this.applyTotalAmount,
                skipOrderIds: this.clientPagination.deletedList.map((d)=>{return d.orderId;})
            };
            instance({
                method: 'post',
                url: apiUrls.receive.declareCommit,
                data: param
            }).then(function (data) {
                if(data.data.success){
                    self.$emit('commited', data.data.msg);
                } else {
                    // 失败
                }
            }).catch(function (err) {
                console.log(err)
                // self.$emit('commited');
            });
        },

        // 获取店铺
        getShopList(cb) {
            let self = this;
            let param = {
                    id: "0"
                };
                instance({
                    method: 'post',
                    url: apiUrls.receive.shopList,
                    data: param
                }).then(function (data) {
                    self.shopList = data.data.data || [];
                    if(data && data.data && data.data.data && data.data.data.length > 0) {
                        let shops = {};
                        data.data.data.forEach(function(s) {
                            let accounts = s.accounts;
                            accounts && accounts.forEach(function(a) {
                                shops[a] = a;
                            });
                        });
                        let arrShops = [];
                        for(let s in shops) {
                            arrShops.push(s);
                        }
                        self.shopList = arrShops;
                        self.receiverNumber = arrShops[0];
                        // self.handleSearch();
                    } else {
                        self.$error("授权店铺列表为空");
                    }
                }).catch(function (err) {
                    console.log(err)
                });
        },

        // 到处表头文件
        handleDownload() {
            if(!this.list || !this.list.length) {
                this.$message.info('没有订单可导出！');
                return;
            }
            let param = {
                account: this.receiverNumber,
                begin: this.begin,
                end: this.end,
                total: this.applyTotalAmount,
                skipOrderIds: this.clientPagination.deletedList.map((d)=>{return d.orderId;}).join(',')
            };

            instance({
                method: 'post',
                url: '/v1/declare/export/payment',//?begin='+param.begin+'&end='+param.end+'&total='+param.total+'&account='+param.account+'&skipOrderIds='+param.skipOrderIds,
                params :param,
                responseType: 'blob'
            }).then(function (data) {
                console.log(data)
                if (data.data.success) {
                    vm.$alert('下载失败！', '提示', {
                    confirmButtonText: '确定',
                    });
                } else {
                    download(data, "国收申报.xlsx");
                }
            });
        }
    },

    computed: {
        totalAmount() {
            if(this.list && this.list.length) {
                let total = floatAdd(this.list.map((item)=>{
                    return item.total;
                }));

                return total;
            }

            return '';
        }
    },
    created() {
        this.clientPagination = new ClientPagination();
        this.clientPagination.rows = this.searchParam.rows;
        this.getShopList();
    }
}
</script>
<style scoped>
.el-date-editor {
    width: 100%;
}

.el-range-separator {
    width: 22px!important;
}
</style>
